from selenium.webdriver.common.by import By
from selenium import webdriver
from time import sleep

# 准备账号密码
userinfo = {'account': 'my.sadness', 'password': 'z6677850j'}


class Email163:
    def __init__(self):
        self.driver = webdriver.Chrome()
        self.driver.get('https://mail.163.com')
        self.driver.maximize_window()

    def login(self):
        # 切换登录框架
        login_module = self.driver.find_element(By.TAG_NAME, 'iframe')
        self.driver.switch_to.frame(login_module)
        # 定位邮箱账号输入框,并清空上一次登录的账号
        self.driver.find_element(By.NAME, 'email').clear()
        # 输入邮箱账号
        self.driver.find_element(By.NAME, 'email').send_keys(userinfo['account'])
        # 定位密码输入框,输入密码
        self.driver.find_element(By.NAME, 'password').send_keys(userinfo['password'])
        # 定位登录按钮,并点击
        self.driver.find_element(By.ID, 'dologin').click()
        sleep(4)

    def write_mail(self):
        # 定位写信按钮,并点击
        btn1 = self.driver.find_element(By.XPATH, '//*[@id="_mail_component_149_149"]/span[2]')
        btn1.click()
        sleep(2)
        # 切换到内容frame
        content_frame = self.driver.find_element(By.CLASS_NAME, 'APP-editor-iframe')
        self.driver.switch_to.frame(content_frame)
        sleep(1)
        # 定位内容输入框,输入
        self.driver.find_element(By.XPATH, '/html/body/p').send_keys('good good study!')
        # 切换回默认frame
        self.driver.switch_to.default_content()
        sleep(1)
        # 定位收件人输入框,输入
        self.driver.find_element(By.CLASS_NAME, 'nui-editableAddr-ipt').send_keys('2868266666@qq.com')
        sleep(1)
        # 定位主题输入框,输入
        self.driver.find_element(By.XPATH, '//input[contains(@id, "subjectInput")]').send_keys('Test')
        # 定位发送按钮,点击
        sleep(2)
        self.driver.find_element(By.XPATH, '//footer[@class="jp0"]/div/span[2]').click()

    def quit(self):
        sleep(3)
        self.driver.quit()


if __name__ == '__main__':
    email163 = Email163()
    email163.login()
    email163.write_mail()
    email163.quit()
